<template>
	<view>
		<view v-for="item in shop">
			<!-- 图文卡片模式 -->
			<uni-card mode="style" :is-shadow="true" :thumbnail="item.imgSrc[0].imgSrc">
				<text class="small">商品名：{{item.name}}</text>
				<br />
				<text class="small">{{item.price}}元/件x{{item.number}}件=<text
						style="font-size: large;">{{item.price*item.number}}</text>元</text>
				<!-- 商品数量按钮 -->
				<view @click="changeNum(item)">
					<uni-number-box :min="0" v-model="item.number" />
				</view>
				<br />
			</uni-card>

		</view>
		<view class="position-sticky fixed-bottom">
			<button type="warn" size="mini" style="margin-bottom: -20rpx;">共计：{{allPrice}}</button>
			<button type="warn" size="mini" style="margin-bottom: -20rpx; margin-left: 3rpx;"
				@click="submitShopCar()">立即结算</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				username: uni.getStorageSync("token"),
				/* 同步获取用户名 */
				shop: [{
					name: '',
					imgSrc: [{}],
					id: 0,
					weight: 0,
					issueDate: '',
					price: 0,
					number: 1,
				}, ]
			}
		},
		methods: {
			submitShopCar() {
				//销毁当前页面，之后跳转
				uni.navigateTo({
					url: 'submitShopCar?username=' + this.username,
				})
			},
			changeNum(item) {
				console.log(item.number);
				if (item.number == 0) { //当前商品数量减到零，执行删除操作
					uni.request({
						url: 'http://localhost:8081/shopCar/deleteShopCarByNum?username=' + this.username +
							'&id=' + item.id,
						success: (res) => {
							if (res.data.result) {
								// console.log("减到零，删除")
								this.onLoadShopCar();
							}
						},
					})
				} else {
					uni.request({
						url: 'http://localhost:8081/shopCar/updateShopCar',
						method: 'POST',
						data: item,
						success: (res) => {
							if (res.data.result) {
								// console.log("修改成功")
							}
						},
					})
				}
			},
			onLoadShopCar() {
				uni.request({
					url: 'http://localhost:8081/shopCar/selectShopCar?username=' + this.username,
					success: (res) => {
						this.shop = res.data.shop;
					},
				})
			}
		},
		computed: {
			allPrice() {
				let all = 0;
				for (let i = 0; i < this.shop.length; i++) {
					all = all + this.shop[i].number * this.shop[i].price;
				}
				return all;
			}
		},
		onLoad() {
			//加载购物车
			this.onLoadShopCar();
		},
		//监听器
		onShow() {
			//uni获取本地数据API
			uni.getStorage({
				key: 'token', //数据key值，也就是存储数据时的名称
				success: function(res) {
					//数据成功获取，用户已登录
				},
				fail: function(res) {
					//数据未获取成功，用户没有登录，这里直接跳转到登录页面
					uni.navigateTo({
						url: '../user/login',
					});
				},
			})
		},
	}
</script>

<style>
	.small {
		font-size: small;
	}

	.position-sticky {
		position: -webkit-sticky !important;
		position: sticky !important;
	}

	.fixed-bottom {
		position: fixed;
		right: 0;
		bottom: calc(var(--window-bottom) + 3px);
		left: 0;
		z-index: 1030;
		margin-bottom: 6;
		text-align: right;
		margin-right: 30rpx;
	}
</style>
